'use strict';

const { Controller } = require('egg');

class ApiController extends Controller {
  // 添加api
  async createApi () {
    const ctx = this.ctx;
    const info = ctx.request.body;
    try {
      const res = await ctx.service.api.createApi(info);
      ctx.body = {
        code: 200,
        mag: '添加成功',
        data: null
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: '添加失败',
        data: null
      };
    }
  }
  //修改api
  async editApi () {
    const { ctx } = this;
    // console.log(ctx.request.body);
    const { id, api, url, method, instruction } = ctx.request.body;
    // console.log(api, url, method);
    try {
      const result = await ctx.service.api.editApi(id, api, url, method, instruction);
      ctx.body = {
        code: 200,
        msg: '修改成功',
        data: null
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: '修改失败',
        data: null
      };
    }
  }
  //展示api
  async showApi () {
    const ctx = this.ctx;
    const { page, pageSize, apiInfo, apiMethod } = ctx.query;
    try {
      var total = 0;
      var list;
      list = await this.app.mysql.query(
        `select * from api where api like "%${apiInfo}%" and method like "%${apiMethod}%" limit ${(page - 1) * pageSize},${pageSize}`
      );
      if (apiInfo == '' && apiMethod == '') {
        // console.log(1);
        total = await this.app.mysql.query(
          `select count(1) from api`
        );
      } else {
        total = await this.app.mysql.query(
          `select found_rows()`
        );
      }
      // console.log(JSON.parse(JSON.stringify(total)));
      const res = list;
      ctx.body = {
        code: 200,
        mag: 'success',
        data: res,
        total: JSON.parse(JSON.stringify(total))[0]
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: 'fail',
        data: null
      };
    }
  }
  async showAllApi () {
    const ctx = this.ctx;
    try {
      let list = await this.app.mysql.query(
        `select * from api `
      );
      // console.log(JSON.parse(JSON.stringify(total)));
      const res = list;
      ctx.body = {
        code: 200,
        mag: 'success',
        data: res
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: 'fail',
        data: null
      };
    }
  }
  //删除api
  async deleteApi () {
    const { ctx } = this;
    const { id } = ctx.query;
    try {
      const result = ctx.service.api.deleteApi(id);
      ctx.body = {
        code: 200,
        message: '成功',
        data: true
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        message: '失败',
        data: false
      };
    }
  }
}

module.exports = ApiController;
